package com.wlts.wzy.DYOrderModule.controller;//package com.wlts.wzy.DYOrderModule.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.linkedmall.model.v20180116.*;
import com.google.gson.Gson;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.DYGoodsModule.DYapi.DySdk;
import com.wlts.wzy.DYOrderModule.entity.DyOrders;
import com.wlts.wzy.DYOrderModule.service.IDyOrdersService;
import com.wlts.wzy.DYOrderModule.util.DyExpressUtils;
import com.wlts.wzy.DYUserModule.entity.DyOauth;
import com.wlts.wzy.DYUserModule.entity.DyStoreUser;
import com.wlts.wzy.DYUserModule.service.IDyOauthService;
import com.wlts.wzy.DYUserModule.service.IDyStoreUserService;
import com.wlts.wzy.LMGoodsModule.entity.LmAddress;
import com.wlts.wzy.LMGoodsModule.entity.LmSelfGoods;
import com.wlts.wzy.LMGoodsModule.service.ILmAddressService;
import com.wlts.wzy.LMGoodsModule.service.ILmSelfGoodsService;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.request.dy.ChangeDyOrderStatusRequest;
import com.wlts.wzy.api.request.dy.DyOrderAddress;
import com.wlts.wzy.api.request.dy.GetMyDyOrdersRequest;
import com.wlts.wzy.api.request.dy.LogisticsAddToDyApiRequest;
import com.wlts.wzy.api.request.ks.IdsRequest;
import com.wlts.wzy.api.request.lm.*;
import com.wlts.wzy.api.response.dy.LogisticsAddToDyApiResponse;
import com.wlts.wzy.api.response.lm.GetLmOrderExpressResponse;
import com.wlts.wzy.api.response.lm.RefundApplicationDetailResponse;
import com.wlts.wzy.api.vo.DeliveryAddress;
import com.wlts.wzy.api.vo.DyVo.DyPack;
import com.wlts.wzy.api.vo.DyVo.DyShippedOrder;
import com.wlts.wzy.api.vo.DyVo.ExpressName;
import com.wlts.wzy.configBean.DyConfig.DyConfig;
import com.wlts.wzy.configBean.LmConfig.LmConfig;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.expand.MyPage;
import com.wlts.wzy.redisLockModule.config.DistributedLocker;
import com.wlts.wzy.util.AddressResolutionUtil;
import com.wlts.wzy.util.CopyUtils;
import com.wlts.wzy.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.wlts.wzy.KSOrderModule.util.PutOrdersToLmUtil.enableOrder;
import static com.wlts.wzy.configBean.LmConfig.LmConfig.client;

/**
 * <p>
 * 快手订单表 前端控制器
 * </p>
 *
 * @author zhiyong
 * @since 2021-02-28
 */
@Api(tags = "抖音订单表 前端控制器")
@RestController
@RequestMapping("/DYOrderModule/dy-orders")
public class DyOrdersController {
    @Autowired
    private DyConfig dyConfig;
    @Autowired
    private IDyStoreUserService dyStoreUserService;
    @Autowired
    private IDyOauthService dyOauthService;
    @Autowired
    private IDyOrdersService dyOrdersService;
    @Autowired
    private ILmSelfGoodsService lmSelfGoodsService;
    @Autowired
    private ILmAddressService lmAddressService;
    @Autowired
    private DistributedLocker distributedLocker;

    @ApiOperation(value = "获得我的抖音订单")
    @RequestMapping(value = "getMyDyOrders", method = RequestMethod.POST)
    public Result<MyPage<DyOrders>> getMyDyOrders(@RequestBody GetMyDyOrdersRequest request) {

//        System.out.println(dyConfig.toString());

        MyLambdaQueryWrapper<DyStoreUser> userWrapper = new MyLambdaQueryWrapper<>();

        userWrapper.eq(DyStoreUser::getUuid, request.getUserUuid());

        DyStoreUser ksStoreUser = dyStoreUserService.getOne(userWrapper);

        if (ksStoreUser == null) {
            return Result.buildResult(500, "用户不存在");
        }

//        if (ksStoreUser() == null) {
//            return Result.buildResult(500, "用户未授权");
//        }

        MyLambdaQueryWrapper<DyOrders> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.eq(DyOrders::getShopId, ksStoreUser.getDySellerId());

        if (request.getOrderId() != null) {
            wrapper.eq(DyOrders::getOrderId, request.getOrderId());
        }
        if (request.getPutLmStatus() != null) {
            wrapper.eq(DyOrders::getPutLmStatus, request.getPutLmStatus());
        }
        if (request.getSendStatus() != null) {
            wrapper.eq(DyOrders::getSendStatus, request.getSendStatus());
        }
        if (request.getFinalStatus() != null) {
            wrapper.eq(DyOrders::getFinalStatus, request.getFinalStatus());
        }
        if (request.getSelfOrder() != null) {
            wrapper.eq(DyOrders::getSelfOrder, request.getSelfOrder());
        }
        if (StringUtils.isNotEmpty(request.getPostTel())) {
            wrapper.like(DyOrders::getPostTel, request.getPostTel());
        }
        if (StringUtils.isNotEmpty(request.getLmRefundStatus())) {
            wrapper.like(DyOrders::getLmRefundStatus, request.getLmRefundStatus());
        }

        if (StringUtils.isNotEmpty(request.getOutProductId())) {
            wrapper.like(DyOrders::getOutProductId, request.getOutProductId());
        }

        if (StringUtils.isNotEmpty(request.getLmErrMsg())) {
            wrapper.like(DyOrders::getLmErrMsg, request.getLmErrMsg());
        }

        wrapper.orderByDesc(BaseEntity::getCreateDate);

        MyPage<DyOrders> lmSelfGoodsList = dyOrdersService.page(wrapper, request.getCurrentPage(), request.getPageSize(), true);

        return Result.buildResult(lmSelfGoodsList);

    }


    @ApiOperation(value = "DY订单条件大批量推送订单到LM")
    @RequestMapping(value = "batchPutOrderToLm", method = RequestMethod.POST)
    public Result batchPutOrderToLm(@RequestBody GetMyDyOrdersRequest batchRequest) {


        try {
            return distributedLocker.lock("batchPutDyOrderToLm", () -> {

                try {

                    MyLambdaQueryWrapper<DyStoreUser> userWrapper = new MyLambdaQueryWrapper<>();

                    userWrapper.eq(DyStoreUser::getUuid, batchRequest.getUserUuid());

                    DyStoreUser ksStoreUser = dyStoreUserService.getOne(userWrapper);

                    if (ksStoreUser == null) {
                        return Result.buildResult(500, "用户不存在");
                    }

                    if (ksStoreUser.getDySellerId() == null) {
                        return Result.buildResult(500, "用户未授权");
                    }

                    MyLambdaQueryWrapper<DyOrders> wrapper = new MyLambdaQueryWrapper<>();

                    wrapper.eq(DyOrders::getShopId, ksStoreUser.getDySellerId());

                    if (batchRequest.getOrderId() != null) {
                        wrapper.eq(DyOrders::getOrderId, batchRequest.getOrderId());
                    }
                    if (batchRequest.getPutLmStatus() != null) {
                        wrapper.eq(DyOrders::getPutLmStatus, batchRequest.getPutLmStatus());
                    }
                    if (batchRequest.getSendStatus() != null) {
                        wrapper.eq(DyOrders::getSendStatus, batchRequest.getSendStatus());
                    }
                    if (batchRequest.getFinalStatus() != null) {
                        wrapper.eq(DyOrders::getFinalStatus, batchRequest.getFinalStatus());
                    }
                    if (batchRequest.getSelfOrder() != null) {
                        wrapper.eq(DyOrders::getSelfOrder, batchRequest.getSelfOrder());
                    }
                    if (StringUtils.isNotEmpty(batchRequest.getPostTel())) {
                        wrapper.like(DyOrders::getPostTel, batchRequest.getPostTel());
                    }
                    if (StringUtils.isNotEmpty(batchRequest.getLmRefundStatus())) {
                        wrapper.like(DyOrders::getLmRefundStatus, batchRequest.getLmRefundStatus());
                    }

                    if (StringUtils.isNotEmpty(batchRequest.getOutProductId())) {
                        wrapper.like(DyOrders::getOutProductId, batchRequest.getOutProductId());
                    }

                    if (StringUtils.isNotEmpty(batchRequest.getLmErrMsg())) {
                        wrapper.like(DyOrders::getLmErrMsg, batchRequest.getLmErrMsg());
                    }

                    //    int page = 1;


                    List<String> fileSelfOrder = new ArrayList<>();
                    List<String> PutLmStatus = new ArrayList<>();
                    List<String> getStatus = new ArrayList<>();
                    List<String> failOrder = new ArrayList<>();
                    try {
                        while (true) {

                            MyPage<DyOrders> myPage = dyOrdersService.page(wrapper, 1, 100, false);

                            System.out.println("总数：" + myPage.getTotal());

                            //    System.out.println("总数：" + JSON.toJSONString(myPage.getRecords()));

                            List<DyOrders> ordersList = myPage.getRecords();

                            ordersList.forEach(ksOrders -> {

                                if (ksOrders.getSelfOrder() != 1) {
                                    fileSelfOrder.add(ksOrders.getOrderId());
                                }
                                if (ksOrders.getPutLmStatus() != 0 && ksOrders.getPutLmStatus() != 2) {
                                    PutLmStatus.add(ksOrders.getOrderId());
                                }
                                if (ksOrders.getFinalStatus() != 2) {
                                    getStatus.add(ksOrders.getOrderId());
                                }

                            });

                            Result x = getResult(fileSelfOrder, PutLmStatus, getStatus);

                            if (x != null) return x;

                            putDyOrderToLm(failOrder, ordersList);

                            if (myPage.getRecords().size() < 100) {
                                break;
                            }
                            //page += 1;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (failOrder.size() > 0) {
                        return Result.buildResult(500, "推送失败的订单订单：" + JSON.toJSONString(failOrder));
                    }
                    return Result.buildResult();
                } catch (IllegalMonitorStateException e) {
                    e.printStackTrace();
                }
                return null;
            }, 600, 2);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.buildResult(500, "上批订单还未处理完，请稍后再试！");
        }

    }

    @ApiOperation(value = "小批量推送订单到LM")
    @RequestMapping(value = "putOrderToLm", method = RequestMethod.POST)
    public Result putOrderToLm(@RequestBody List<IdsRequest> requests) {

        //       System.out.println(requests);

        List<Integer> ids = requests.stream().map(IdsRequest::getId).collect(Collectors.toList());

        MyLambdaQueryWrapper<DyOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.in(BaseEntity::getId, ids);

        List<DyOrders> ordersList = dyOrdersService.list(queryWrapper);


        List<String> fileSelfOrder = new ArrayList<>();
        List<String> PutLmStatus = new ArrayList<>();
        List<String> getStatus = new ArrayList<>();


        ordersList.forEach(ksOrders -> {

            if (ksOrders.getSelfOrder() != 1) {
                fileSelfOrder.add(ksOrders.getOrderId());
            }
            if (ksOrders.getPutLmStatus() != 0 && ksOrders.getPutLmStatus() != 2) {
                PutLmStatus.add(ksOrders.getOrderId());
            }
            if (ksOrders.getFinalStatus() != 2) {
                getStatus.add(ksOrders.getOrderId());
            }

        });

        Result x = getResult(fileSelfOrder, PutLmStatus, getStatus);
        if (x != null) return x;

        List<String> failOrder = new ArrayList<>();

        putDyOrderToLm(failOrder, ordersList);

        if (failOrder.size() > 0) {
            return Result.buildResult(500, "推送失败的订单订单：" + JSON.toJSONString(failOrder));
        }
        return Result.buildResult();
    }


    @ApiOperation(value = "单个订单向LM发起退款前渲染", notes = "注意：Lm订单“未发货”只能申请“仅退款(BizClaimType=1)”，订单“已发货”只能申请货物状态为“未收到货 (GoodsStatus=1)”或“已收到货(GoodsStatus=2)”")
    @RequestMapping(value = "beforeRefundOrderToLm", method = RequestMethod.POST)
    public Result<InitApplyRefundResponse> beforeRefundOrderToLm(@RequestBody BeforeRefundOrderToLmRequest requests) throws ClientException {

        Set<Long> faildIds = new HashSet<>();

        // List<Integer> ids = requests.getIds();

        MyLambdaQueryWrapper<DyOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());

        DyOrders ksOrders = dyOrdersService.getOne(queryWrapper);


        InitApplyRefundRequest request = new InitApplyRefundRequest();
        request.setBizId(LmConfig.LZ_BIZ_ID);
        request.setAccountType("ANONY");
        request.setThirdPartyUserId(ksOrders.getShopId() + "");
        request.setBizUid(request.getThirdPartyUserId());

        //注意：订单“未发货”只能申请“仅退款(BizClaimType=1)”，订单“已发货”只能申请货物状态为“未收到货 (GoodsStatus=1)”或“已收到货(GoodsStatus=2)”

        //发起退款的⼦订 单，可在查询订单 详情接⼝中获取
        request.setSubLmOrderId(ksOrders.getLmOrderId());
        //4: 未发货, 6: 已 发货, 1: 未收到货, 2: 已收到货, 3: 已寄回, 5: 卖家 确认收货
        request.setGoodsStatus(requests.getGoodsStatus());
        //1 仅退款，3 退货 退款
        request.setBizClaimType(requests.getBizClaimType());

        InitApplyRefundResponse resp = client.getAcsResponse(request);

        return Result.buildResult(resp);
    }


    @ApiOperation(value = "单个订单向LM发起退款")
    @RequestMapping(value = "RefundOrderToLm", method = RequestMethod.POST)
    public Result RefundOrderToLm(@RequestBody RefundOrderToLmRequest requests) {

        //  System.out.println(JSON.toJSONString(requests));

        Set<String> faildIds = new HashSet<>();

        // List<Integer> ids = requests.getIds();

        MyLambdaQueryWrapper<DyOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());
        DyOrders ksOrders = dyOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }

//        if (ksOrders.getLmRefundStatus() != 0 && ksOrders.getLmRefundStatus() != 4) {//lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
//            return Result.buildResult(500, "lm退款申请状态 不为 0未申请 或者  4申请失败");
//        }

        try {
            ApplyRefundRequest applyRefundRequest = new ApplyRefundRequest();
            applyRefundRequest.setBizId(LmConfig.LZ_BIZ_ID);
            applyRefundRequest.setAccountType("ANONY");
            applyRefundRequest.setThirdPartyUserId(ksOrders.getShopId() + "");
            applyRefundRequest.setBizUid(applyRefundRequest.getThirdPartyUserId());
            applyRefundRequest.setBizClaimType(requests.getBizClaimType());
            applyRefundRequest.setGoodsStatus(requests.getGoodsStatus());
            applyRefundRequest.setSubLmOrderId(ksOrders.getLmOrderId());




            BigDecimal price = new BigDecimal(requests.getApplyRefundFee()).multiply(BigDecimal.valueOf(100));

            applyRefundRequest.setApplyRefundFee(price.longValue());
            applyRefundRequest.setApplyReasonTextId(requests.getReasonTextId());

            if (!StringUtils.isEmpty(requests.getLeaveMessage())) {
                applyRefundRequest.setLeaveMessage(requests.getLeaveMessage());
            }

            if (requests.getPicRequestList().size() > 0) {
                List<ApplyRefundRequest.LeavePictureList> leavePictureLists = new ArrayList<>();
                requests.getPicRequestList().forEach(refundOrderToLmPicRequest -> {
                    ApplyRefundRequest.LeavePictureList picture = new ApplyRefundRequest.LeavePictureList();
                    picture.setPicture(refundOrderToLmPicRequest.getPicture());
                    picture.setDesc(refundOrderToLmPicRequest.getPicture());
                    leavePictureLists.add(picture);
                });
                applyRefundRequest.setLeavePictureLists(leavePictureLists);
            }

            ApplyRefundResponse applyRefundResponse = client.getAcsResponse(applyRefundRequest);

            ksOrders.setLmRefundMsg(JSON.toJSONString(applyRefundResponse));

            // System.out.println(JSON.toJSONString(applyRefundResponse));

            if (applyRefundResponse.getCode().equals("SUCCESS")) {
                //lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
                ksOrders.setLmRefundStatus(1);
            } else {
                faildIds.add(ksOrders.getOrderId());
                ksOrders.setLmRefundStatus(4);
                return Result.buildResult(500, "LM发起退款失败 原因如下：" + applyRefundResponse.getMessage());
            }
            dyOrdersService.updateById(ksOrders);

        } catch (ClientException e) {
            faildIds.add(ksOrders.getOrderId());
            e.printStackTrace();
        }
        if (faildIds.size() > 0) {
            return Result.buildResult(500, "退款失败订单如下：" + JSON.toJSONString(faildIds));
        }
        return Result.buildResult();
    }


    @ApiOperation(value = "LM查询退款申请详情")
    @RequestMapping(value = "queryRefundApplicationDetail", method = RequestMethod.POST)
    public Result<RefundApplicationDetailResponse> queryRefundApplicationDetail(@RequestBody LmQueryRefundApplicationDetailRequest requests) {

        MyLambdaQueryWrapper<DyOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());
        DyOrders ksOrders = dyOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }

        if (ksOrders.getLmRefundStatus() == 0) {//lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
            return Result.buildResult(500, "订单未向LM申请退款");
        }

        try {
            QueryRefundApplicationDetailRequest applyRefundRequest = new QueryRefundApplicationDetailRequest();
            applyRefundRequest.setBizId(LmConfig.LZ_BIZ_ID);
            applyRefundRequest.setAccountType("ANONY");
            applyRefundRequest.setThirdPartyUserId(ksOrders.getShopId() + "");
            applyRefundRequest.setBizUid(applyRefundRequest.getThirdPartyUserId());
            applyRefundRequest.setSubLmOrderId(ksOrders.getLmOrderId());

            QueryRefundApplicationDetailResponse applyRefundResponse = client.getAcsResponse(applyRefundRequest);

            RefundApplicationDetailResponse response = JSON.toJavaObject(JSON.parseObject(JSON.toJSONString(applyRefundResponse)), RefundApplicationDetailResponse.class);

            return Result.buildResult(response);

        } catch (ClientException e) {

            e.printStackTrace();
        }
        return Result.buildResult();
    }


    @ApiOperation(value = "Dy单个订单向LM发起取消退款")
    @RequestMapping(value = "lmCancelRefund", method = RequestMethod.POST)
    public Result lmCancelRefund(@RequestBody LmCancelRequest requests) {

        Set<String> faildIds = new HashSet<>();

        // List<Integer> ids = requests.getIds();

        MyLambdaQueryWrapper<DyOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());
        DyOrders ksOrders = dyOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }

        if (ksOrders.getLmRefundStatus() != 1) {//lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
            return Result.buildResult(500, "lm退款申请不为状态 1已申请");
        }

        try {
            CancelRefundRequest applyRefundRequest = new CancelRefundRequest();
            applyRefundRequest.setBizId(LmConfig.LZ_BIZ_ID);
            applyRefundRequest.setAccountType("ANONY");
            applyRefundRequest.setThirdPartyUserId(ksOrders.getShopId() + "");
            applyRefundRequest.setBizUid(applyRefundRequest.getThirdPartyUserId());
            applyRefundRequest.setSubLmOrderId(ksOrders.getLmOrderId());
            applyRefundRequest.setDisputeId(requests.getDisputeId());

            CancelRefundResponse applyRefundResponse = client.getAcsResponse(applyRefundRequest);

            ksOrders.setLmRefundMsg(JSON.toJSONString(applyRefundResponse));

            if (applyRefundResponse.getCode().equals("SUCCESS")) {
                //lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败 5已取消 6已提交物流 7提交物流失败 8取消退款失败
                ksOrders.setLmRefundStatus(5);
            } else {
                faildIds.add(ksOrders.getOrderId());
                ksOrders.setLmRefundStatus(8);
            }
            dyOrdersService.updateById(ksOrders);

        } catch (ClientException e) {
            faildIds.add(ksOrders.getOrderId());
            e.printStackTrace();
        }
        if (faildIds.size() > 0) {
            return Result.buildResult(500, "取消退款失败订单如下：" + JSON.toJSONString(faildIds));
        }
        return Result.buildResult();
    }


    @ApiOperation(value = "修改DY订单状态")
    @RequestMapping(value = "changeOrderStatus", method = RequestMethod.POST)
    public Result changeOrderStatus(@RequestBody ChangeDyOrderStatusRequest requests) {

        MyLambdaQueryWrapper<DyOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());

        DyOrders ksOrders = dyOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }
        ksOrders.setPutLmStatus(requests.getPutLmStatus());
        if (StringUtils.isNotEmpty(requests.getPostAddr())) {
            ksOrders.setPostAddr(requests.getPostAddr());
        }

        CopyUtils.copyProperties(requests,ksOrders);

        dyOrdersService.updateById(ksOrders);
        return Result.buildResult();
    }


    @ApiOperation(value = "推送快递单号到dy")
    @RequestMapping(value = "putExpressToDy", method = RequestMethod.POST)
    public Result putExpressToDy(@RequestBody IdsRequest requests) {


        DyOrders ksOrders = dyOrdersService.getById(requests.getId());

        if (ksOrders == null) {
            return Result.buildResult(500, "订单存在！");
        }

        if (ksOrders.getPutLmStatus() == 0) {//推送lm状态 0未推送 1已推送 2推送失败
            return Result.buildResult(500, "订单未推送！");
        }

        if (ksOrders.getPutExpressStatus() == 1) {//推送物流状态 0未推送，1已经推送 2推送失败
            return Result.buildResult(500, "快递单号已经推送！");
        }

        if (ksOrders.getLmOrderId() == null) {//推送物流状态 0未推送，1已经推送 2推送失败
            return Result.buildResult(500, "lm单号为空！");
        }

        QueryLogisticsRequest request = new QueryLogisticsRequest();
        request.setBizId(LmConfig.LZ_BIZ_ID);
        request.setAccountType("ANONY");
        request.setThirdPartyUserId(ksOrders.getShopId() + "");
        request.setBizUid(request.getThirdPartyUserId());
        request.setLmOrderId(Long.valueOf(ksOrders.getLmOrderId()));

        try {
            QueryLogisticsResponse response = client.getAcsResponse(request);

            System.out.println(response);

            if (response.getCode().equals("SUCCESS")) {
                List<QueryLogisticsResponse.DataItem> data = response.getData();
                QueryLogisticsResponse.DataItem item = data.get(0);

                if (item != null) {

                    if (!StringUtils.isNotEmpty(item.getMailNo())) {
                        return Result.buildResult(500, "快递单号不存在！");
                    }


                    ksOrders.setExpressNo(item.getMailNo());
                    ksOrders.setExpressName(item.getLogisticsCompanyName());
                    //    DyExpressCode expressCode = ksExpressCodeService.getOne(new MyLambdaQueryWrapper<DyExpressCode>().like(DyExpressCode::getName, item.getLogisticsCompanyName()));

                    List<ExpressName> expressNameList = DyExpressUtils.likeString(item.getLogisticsCompanyName());

                    System.out.println(JSON.toJSONString(expressNameList));

                    if (expressNameList.size() > 0) {
                        ksOrders.setExpressCode(expressNameList.get(0).getId());
                    }


                    GetLmOrderExpressResponse expressResponse = new GetLmOrderExpressResponse();

                    CopyUtils.copyProperties(item, expressResponse);

                    MyLambdaQueryWrapper<DyStoreUser> userWrapper = new MyLambdaQueryWrapper<>();

                    userWrapper.eq(DyStoreUser::getDelFlag, "0");

                    userWrapper.isNotNull(DyStoreUser::getDySellerId);

                    userWrapper.eq(DyStoreUser::getDySellerId, ksOrders.getShopId());

                    DyStoreUser user = dyStoreUserService.getOne(userWrapper);

                    MyLambdaQueryWrapper<DyOauth> oauthWrapper = new MyLambdaQueryWrapper<>();

                    oauthWrapper.eq(DyOauth::getDelFlag, "0");

                    oauthWrapper.eq(DyOauth::getUserUuid, user.getUuid());

                    DyOauth ksOauth = dyOauthService.getOne(oauthWrapper);

                    LogisticsAddToDyApiRequest addToDyApiRequest = new LogisticsAddToDyApiRequest();

                    addToDyApiRequest.setOrder_id(ksOrders.getPid());

                    addToDyApiRequest.setRequest_id(UUID.randomUUID().toString());

                    DyPack pack = new DyPack();

                    DyShippedOrder shippedOrder = new DyShippedOrder();

                    shippedOrder.setShipped_num(ksOrders.getComboNum());
                    shippedOrder.setShipped_order_id(ksOrders.getOrderId());

                    List<DyShippedOrder> shippedOrders = new ArrayList<>();
                    shippedOrders.add(shippedOrder);

                    pack.setShipped_order_info(shippedOrders);

                    pack.setLogistics_code(ksOrders.getExpressNo());
                    pack.setLogistics_id(ksOrders.getExpressCode() + "");

                    List<DyPack> dyPackList = new ArrayList<>();
                    dyPackList.add(pack);
                    addToDyApiRequest.setPack_list(JSON.toJSONString(dyPackList));


                    LogisticsAddToDyApiResponse dyApiResponse = DySdk.LogisticsAddSinglePack(user.getAppKey(), user.getAppSecret(), ksOauth.getAccessToken(), addToDyApiRequest);


                    //  System.out.println(dyApiResponse.toString());

                    if (dyApiResponse.getErr_no() == 0) {
                        ksOrders.setPutExpressStatus(1);
                    } else {
                        ksOrders.setPutExpressStatus(2);
                    }
                    ksOrders.setKsErrMsg(JSON.toJSONString(dyApiResponse));

                    dyOrdersService.updateById(ksOrders);

                    return Result.buildResult(expressResponse);
                }

            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.buildResult(500, "快递单号不存在！");


    }


    @ApiOperation(value = "Lm提交退货物流信息接⼝")
    @RequestMapping(value = "lmSubmitReturnGoodLogistics", method = RequestMethod.POST)
    public Result lmSubmitReturnGoodLogistics(@RequestBody LmSubmitReturnGoodLogisticsRequest requests) {

        System.out.println(requests);

        Set<String> faildIds = new HashSet<>();

        // List<Integer> ids = requests.getIds();

        MyLambdaQueryWrapper<DyOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());
        DyOrders ksOrders = dyOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }

//        if (ksOrders.getLmRefundStatus() != 1) {//lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
//            return Result.buildResult(500, "lm退款申请不为状态 1已申请");
//        }

        try {
            SubmitReturnGoodLogisticsRequest applyRefundRequest = new SubmitReturnGoodLogisticsRequest();

            applyRefundRequest.setAccountType("ANONY");
            applyRefundRequest.setThirdPartyUserId(ksOrders.getShopId() + "");
            applyRefundRequest.setBizUid(applyRefundRequest.getThirdPartyUserId());
            applyRefundRequest.setBizId(LmConfig.LZ_BIZ_ID);
            applyRefundRequest.setSubLmOrderId(requests.getSubLmOrderId());
            applyRefundRequest.setDisputeId(Long.valueOf(requests.getDisputeId()));
            applyRefundRequest.setLogisticsNo(requests.getLogisticsNo());
            applyRefundRequest.setCpCode(requests.getCpCode());


            SubmitReturnGoodLogisticsResponse applyRefundResponse = client.getAcsResponse(applyRefundRequest);

            System.out.println(JSON.toJSONString(applyRefundResponse));

            ksOrders.setLmRefundMsg(JSON.toJSONString(applyRefundResponse));

            if (applyRefundResponse.getCode().equals("SUCCESS")) {
                //lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败 5已取消 6已提交物流 7提交物流失败 8取消退款失败
                ksOrders.setLmRefundStatus(6);
            } else {
                faildIds.add(ksOrders.getOrderId());
                ksOrders.setLmRefundStatus(7);
            }
            dyOrdersService.updateById(ksOrders);

        } catch (ClientException e) {
            faildIds.add(ksOrders.getOrderId());
            e.printStackTrace();
            return Result.buildResult(500, e.getMessage());
        }
        if (faildIds.size() > 0) {
            return Result.buildResult(500, "提交退货物流失败订单如下：" + JSON.toJSONString(faildIds));
        }
        return Result.buildResult();
    }


    private Result getResult(List<String> fileSelfOrder, List<String> putLmStatus, List<String> getStatus) {

        if (fileSelfOrder.size() > 0) {
            return Result.buildResult(500, "订单不为平台推送商品订单 单号如下：" + JSON.toJSONString(fileSelfOrder));
        }
        if (putLmStatus.size() > 0) {
            return Result.buildResult(500, "订单不为未推送订单或者推送失败订单 单号如下：" + JSON.toJSONString(putLmStatus));
        }
        if (getStatus.size() > 0) {
            return Result.buildResult(500, "订单已支付未发货订单 单号如下：" + JSON.toJSONString(getStatus));
        }
        return null;
    }

    private void putDyOrderToLm(List<String> failOrder, List<DyOrders> ordersList) {
        ordersList.forEach(ksOrders -> {

//[{"buyerId":0,"createTime":1612605117278,"discountFee":0,"id":8283462433580,"itemId":943491185290,"itemLinkUrl":"https://app.kwaixiaodian.com/merchant/shop/detail?id=943491185290&hyId=kwaishop&layoutType=4","itemPicUrl":"https://ali-ec.static.yximgs.com/ufile/adsocial/87243885-9d23-45e8-bd5d-d15dac7df6c0.jpg","itemTitle":"【瑜大直播】艺品赞红豆薏米茶150g*1袋","itemType":1,"num":1,"oid":2103700006986580,"originalPrice":990,"price":990,"refundId":2103700007004580,"refundList":[{"refundId":2103700007004580,"refundStatus":10}],"refundStatus":10,"relItemId":1612577579226,"relSkuId":0,"skuDesc":"红豆薏米茶","skuId":943491186290,"updateTime":1612605117278}]


            MyLambdaQueryWrapper<LmSelfGoods> selfGoodsWrapper = new MyLambdaQueryWrapper<>();

            selfGoodsWrapper.eq(LmSelfGoods::getRelItemId, ksOrders.getOutProductId());

            LmSelfGoods lmSelfGoods = lmSelfGoodsService.getOne(selfGoodsWrapper);

            if (lmSelfGoods != null) {
                //    if(ksOrders.getStatus()==30){
                CreateOrderV2Request request = new CreateOrderV2Request();
                CreateOrderV2Request.ItemList itemList = new CreateOrderV2Request.ItemList();
                DeliveryAddress deliveryAddress = new DeliveryAddress();
                request.setBizId(LmConfig.LZ_BIZ_ID);
                request.setAccountType("ANONY");
                request.setThirdPartyUserId(ksOrders.getShopId() + "");
                request.setBizUid(request.getThirdPartyUserId());

                List<CreateOrderV2Request.ItemList> itemLists = new ArrayList<>();

                request.setOutTradeId(ksOrders.getOrderId() + "");

                itemList.setLmItemId(lmSelfGoods.getLmItemId() + "");
                itemList.setQuantity(ksOrders.getComboNum());
                if (ksOrders.getOutSkuId() != 0) {
                    itemList.setSkuId(ksOrders.getOutSkuId());
                } else {
                    if (ksOrders.getCode() != null) {
                        itemList.setSkuId(Long.valueOf(ksOrders.getCode()));
                    }
                }


                DyOrderAddress ksOrdersAddress = JSONObject.parseObject(ksOrders.getPostAddr(), DyOrderAddress.class);

                /**
                 * 设置地址
                 */
                deliveryAddress.setFullName(ksOrders.getPostReceiver());
                deliveryAddress.setMobile(ksOrders.getPostTel());
                // deliveryAddress.setAddressDetail(ksOrdersAddress.getProvince().getName() + ksOrdersAddress.getCity().getName() + ksOrdersAddress.getTown().getName() + ksOrdersAddress.getDetail());
                deliveryAddress.setAddressDetail(ksOrdersAddress.getDetail());
                MyLambdaQueryWrapper<LmAddress> provinceWrapper = new MyLambdaQueryWrapper<>();

                provinceWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince().getName());

                provinceWrapper.eq(LmAddress::getParentId, 1);

                LmAddress province = lmAddressService.getOne(provinceWrapper);

                if (province == null) {
                    MyLambdaQueryWrapper<LmAddress> provinceWrapper2 = new MyLambdaQueryWrapper<>();

                    provinceWrapper2.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince().getName().replace("市", ""));

                    provinceWrapper2.eq(LmAddress::getParentId, 1);
                    province = lmAddressService.getOne(provinceWrapper2);
                }

                if (province != null) {
                    MyLambdaQueryWrapper<LmAddress> cityWrapper = new MyLambdaQueryWrapper<>();

                    cityWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getCity().getName());

                    cityWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                    LmAddress city = lmAddressService.getOne(cityWrapper);

                    boolean jump = false;

                    if (city == null) {
                        if (ksOrdersAddress.getCity().getName().equals("市辖区") || ksOrdersAddress.getCity().getName().equals("县")) {

                            MyLambdaQueryWrapper<LmAddress> cityWrapper1 = new MyLambdaQueryWrapper<>();

                            cityWrapper1.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince().getName());

                            cityWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                            city = lmAddressService.getOne(cityWrapper1);
                        } else {
                            if (ksOrdersAddress.getCity().getName().equals("自治区直辖县级行政区划") || ksOrdersAddress.getCity().getName().equals("省直辖县级行政区划")) {
                                jump = true;
                            }
                        }
                    }
                    if (city == null && !jump) {
                        System.out.println("系统不存在" + ksOrdersAddress.getProvince().getName() + "省下的：" + ksOrdersAddress.getCity().getName());

                        ksOrders.setPutLmStatus(2);
                        ksOrders.setLmErrMsg("{\"code\":\"NO_ADDRESS\",\"logsId\":\"\",\"message\":\"" + "系统不存在" + ksOrdersAddress.getProvince().getName() + "省下的：" + ksOrdersAddress.getCity().getName() + "\",\"model\":{\"lmOrderList\":[],\"orderIds\":[],\"payTradeIds\":[],\"redirectUrl\":\"\"},\"requestId\":\"local\",\"subCode\":\"\",\"subMessage\":\"\",\"success\":true}");
                        dyOrdersService.updateById(ksOrders);

                    } else {
                        LmAddress dest;
                        if (jump) {
                            MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                            destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getTown().getName());

                            destWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                            dest = lmAddressService.getOne(destWrapper);
                        } else {
                            MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                            destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getTown().getName());

                            destWrapper.eq(LmAddress::getParentId, city.getDivisionCode());

                            dest = lmAddressService.getOne(destWrapper);
                        }

                        if (dest == null) {

                            if (jump) {
                                MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                destWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                                dest = lmAddressService.getOne(destWrapper1);
                            } else {
                                MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                destWrapper1.eq(LmAddress::getParentId, city.getDivisionCode());

                                dest = lmAddressService.getOne(destWrapper1);
                            }

                            if (dest == null) {
                                System.out.println("系统不存在" + ksOrdersAddress.getProvince().getName() + "省下：" + ksOrdersAddress.getCity().getName() + "市的区：" + ksOrdersAddress.getTown().getName());

                                ksOrders.setPutLmStatus(2);
                                ksOrders.setLmErrMsg("{\"code\":\"NO_ADDRESS\",\"logsId\":\"\",\"message\":\"" + "系统不存在" + ksOrdersAddress.getProvince().getName() + "省下：" + ksOrdersAddress.getCity().getName() + "市的区：" + ksOrdersAddress.getTown().getName() + "\",\"model\":{\"lmOrderList\":[],\"orderIds\":[],\"payTradeIds\":[],\"redirectUrl\":\"\"},\"requestId\":\"local\",\"subCode\":\"\",\"subMessage\":\"\",\"success\":true}");
                                dyOrdersService.updateById(ksOrders);

                            }


                        }

                        if (dest != null) {

                            deliveryAddress.setDivisionCode(dest.getDivisionCode() + "");

                            List<Map<String, String>> table = AddressResolutionUtil.addressResolution(ksOrdersAddress.getDetail());

                            if (table.size() > 0) {

                                String townName = table.get(0).get("town");

                                if (!StringUtils.isEmpty(townName)) {

                                    //    System.out.println("街道名字："+townName);

                                    MyLambdaQueryWrapper<LmAddress> townWrapper = new MyLambdaQueryWrapper<>();

                                    townWrapper.like(LmAddress::getDivisionName, townName);

                                    townWrapper.eq(LmAddress::getParentId, dest.getDivisionCode());

                                    LmAddress town = lmAddressService.getOne(townWrapper);

                                    if (town != null) {
                                        //    System.out.println("街道："+town.toString());
                                        deliveryAddress.setTownDivisionCode(town.getDivisionCode() + "");
                                    }
                                }
                            }

                            itemLists.add(itemList);

                            request.setItemLists(itemLists);

                            //    System.out.println("地址详细："+JSON.toJSONString(deliveryAddress));

                            request.setDeliveryAddress(JSON.toJSONString(deliveryAddress));

                            try {
                                System.out.println("请求内容："+JSON.toJSONString(request));
                                //创建订单
                                CreateOrderV2Response resp = client.getAcsResponse(request);

                                if (resp.getCode().equals("SUCCESS")) {

                                    ksOrders.setLmOrderId(resp.getModel().getLmOrderList().get(0).getLmOrderId());
                                    ksOrders.setTbOrderId(resp.getModel().getOrderIds().get(0));

                                    EnableOrderResponse enableOrderResponse = enableOrder(request.getOutTradeId(), resp.getModel().getLmOrderList().get(0).getLmOrderId(), ksOrders.getShopId() + "");

                                    if (enableOrderResponse.getCode().equals("SUCCESS")) {
                                        ksOrders.setPutLmStatus(1);
                                    } else {
                                        System.out.println("报文内容：" + JSON.toJSONString(enableOrderResponse));
                                        ksOrders.setPutLmStatus(2);
                                        failOrder.add(ksOrders.getOrderId() + "");
                                    }

                                    ksOrders.setLmErrMsg(JSON.toJSONString(enableOrderResponse));
                                } else {
                                    System.out.println("报文内容：" + JSON.toJSONString(resp));
                                    //  failOrder.add(ksOrders.getOrderId() + "");
                                    if (resp.getCode().equals("CALL_TRADE_SRVICE_FAIL")) {
                                        System.out.println("跳过保存");
                                    } else if (resp.getCode().equals("CREATE_ORDER_REPEATE")) {
                                        if (StringUtils.isNotEmpty(ksOrders.getLmOrderId())) {
                                            EnableOrderResponse enableOrderResponse = enableOrder(request.getOutTradeId(), ksOrders.getLmOrderId(), ksOrders.getShopId() + "");
                                            if (enableOrderResponse.getCode().equals("SUCCESS")) {
                                                ksOrders.setPutLmStatus(1);
                                            } else {
                                                ksOrders.setPutLmStatus(2);
                                                failOrder.add(ksOrders.getOrderId() + "");
                                                ksOrders.setLmErrMsg(JSON.toJSONString(enableOrderResponse));
                                            }
                                            System.out.println("跳过保存");
                                        } else {
                                            ksOrders.setPutLmStatus(2);
                                            ksOrders.setLmErrMsg(JSON.toJSONString(resp));
                                        }
                                    } else {
                                        ksOrders.setPutLmStatus(2);
                                        ksOrders.setLmErrMsg(JSON.toJSONString(resp));
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            dyOrdersService.updateById(ksOrders);
                        } else {
                            ksOrders.setPutLmStatus(2);
                            ksOrders.setLmErrMsg("{\"code\":\"NO_ADDRESS\",\"logsId\":\"\",\"message\":\"无对应地址\",\"model\":{\"lmOrderList\":[],\"orderIds\":[],\"payTradeIds\":[],\"redirectUrl\":\"\"},\"requestId\":\"120F7222-4C88-4FC5-BD7E-3A9B3557F32D\",\"subCode\":\"\",\"subMessage\":\"\",\"success\":true}");
                            dyOrdersService.updateById(ksOrders);
                        }
                    }
                } else {
                    System.out.println("系统不存在省份：" + ksOrdersAddress.getProvince().getName());

                    ksOrders.setPutLmStatus(2);
                    ksOrders.setLmErrMsg("{\"code\":\"NO_ADDRESS\",\"logsId\":\"\",\"message\":\"" + "系统不存在省份：" + ksOrdersAddress.getProvince().getName() + "\",\"model\":{\"lmOrderList\":[],\"orderIds\":[],\"payTradeIds\":[],\"redirectUrl\":\"\"},\"requestId\":\"local\",\"subCode\":\"\",\"subMessage\":\"\",\"success\":true}");
                    dyOrdersService.updateById(ksOrders);
                }
            }

        });
    }


}
